package data

import (
	"context"
	"gitee.com/byx_darwin/geo-rpc/internal/base/conf"
	"github.com/cloudwego/kitex/pkg/klog"
	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
	"github.com/oschwald/geoip2-golang"
)

type Data struct {
	Log      klog.CtxLogger
	Conf     *conf.Config
	Searcher *xdb.Searcher
	CityDB   *geoip2.Reader
	IspDB    *geoip2.Reader
}

func NewData(c *conf.Config, log klog.CtxLogger) (*Data, func(), error) {
	ctx := context.Background()
	cBuff, err := xdb.LoadContentFromFile(c.GeoOption.Ip2RegionPath)
	if err != nil {
		log.CtxFatalf(ctx, "xdb LoadContentFromFile failure,err:%v", err)
	}
	searcher, err := xdb.NewWithBuffer(cBuff)
	if err != nil {
		log.CtxFatalf(ctx, "xdb NewWithBuffer failure,err:%s", err.Error())
	}
	cityDB, err := geoip2.Open(c.GeoOption.GeoIPCityPath)
	if err != nil {
		log.CtxFatalf(ctx, "cityDB Open failure,err:%s", err.Error())
	}
	ispDB, err := geoip2.Open(c.GeoOption.GeoIPIspPath)
	if err != nil {
		log.CtxFatalf(ctx, "isp Open failure,err:%s", err.Error())
	}

	d := &Data{
		Log:      log,
		Conf:     c,
		Searcher: searcher,
		CityDB:   cityDB,
		IspDB:    ispDB,
	}
	return d, func() {
		if err := cityDB.Close(); err != nil {
			log.CtxErrorf(ctx, "cityDB Close failure,err:%s", err.Error())
		}
		if err := ispDB.Close(); err != nil {
			log.CtxErrorf(ctx, "ispDB Close failure,err:%s", err.Error())
		}
	}, nil
}
